/**
 * 庭审直播
 */
var time;
//var ue;
var tmpinterVal;
var statTime;
$(function(){
	//浏览器不支持indexOf方法时添加indexOf
	addIndeOf();
	if(status==0){
		openStartButton();
		colsePaurseButton();
		colseStopButton();
	}
	if(status==1){
		colseStartButton();
		openPaurseButton();
		openStopButton();
		TimeFunc(length);
	}
	if(status==4){
		openStartButton();
		colsePaurseButton();
		openStopButton();
	}
	if(status==2){
		$("#stopcourt").attr("src",$Path+"/public/images/button_stop_normal.png");
		colseStartButton();
		colsePaurseButton();
		colseStopButton();
	}
	var divWidth=$("#content").width();
	$("#vlc").css("width",divWidth+"px");
	var caseid=$("#caseid").val();
	tmpinterVal=setInterval(function(){
		if(ue.body!=undefined){
			ue.registerCommand('ceshi',{
				execCommand:function(){
					ue.execCommand("inserthtml","<a style='color:red;cursor:pointer'>|</a>&nbsp;");
				}
			});
			ue.addshortcutkey({
				"ceshi":"113"
			});
			window.clearInterval(tmpinterVal);
			$.ajax({
				type:'get',
				url:$Path+'/admin/getLiveContent',
				data:{caseid:caseid},
				success:function(data){
					if(data.code==200){
						var content=data.results;
						ue.setContent(content);
//						ue.options.initialContent=content;
						if(length!=''&&length!=undefined){
							setTime(length);
						}
						initUe();
					}
				}
			})
		}
	},1000);
})
//浏览器不支持indexOf方法时添加indexOf
function addIndeOf(){
	if (!Array.prototype.indexOf){
		Array.prototype.indexOf = function(elt /*, from*/){
	    var len = this.length >>> 0;

	    var from = Number(arguments[1]) || 0;
	    from = (from < 0)
	         ? Math.ceil(from)
	         : Math.floor(from);
	    if (from < 0)
	      from += len;

	    for (; from < len; from++){
	      if (from in this && this[from] === elt)
	        return from;
	    }
	    return -1;
	  };
	}
}
/**
 * 状态为开庭时打开轮询
 */
function initUe(){
	if(status==1){
		isfind=true;
		colseStartButton();
		openPaurseButton();
		openStopButton();
		findnew();
	}
}
/**
 * 添加词汇
 */
function addWord(){
	var context = $("#content").val();
	var caseid = $("#caseid").val();
	var auth=window.parent.getAuth();
	if(context.length>100){
		parent.$.messager.alert('失败',"词条内容不可大于100个字",'error');
		return false;
	}
	$.ajax({
		type:"post",
		data:{'drWord.context':context,'drWord.caseid':caseid,authenticityToken:auth},
		url:$Path+'/admin/caseWord/addCaseWord',
		success:function(data){
			if(data.code==200){
				$("#content").val('')
				refreshWord();
			}
			else{
				parent.$.messager.alert('失败',data.msg,'error');
			}
		},
		error:function(data){
			parent.$.messager.alert('失败',"网络错误",'error');
		}
	})
	
	
}

function refreshWord(){
	var caseid = $("#caseid").val();
	$.ajax({
		type:"get",
		data:{caseid:caseid},
		url:$Path+'/admin/caseWord/findCaseWordByCaseId',
		success:function(data){
			var html = "";
			for(var i = 0;i<data.results.length;i++){
				html+='<li class="titleli ">'+
						'<span class="titlespan" ondblclick="changeContent(\''+data.results[i].context+'\',\''+data.results[i].casewordid+'\')">'+data.results[i].context+'</span>'+
						'<img src="'+$Path+'/public/images/icon_delete.png" class="titleimg" onclick="delkeyword(\''+data.results[i].casewordid+'\')">'+
					'</li>';
			}
			$(".shaixuan").html(html);
		},
		error:function(data){
			parent.$.messager.alert('失败',"网络错误",'error');
		}
	})
}

function delkeyword(casewordid){
	parent.$.messager.confirm('删除','您确定要删除该词条吗？',function(data){
		if(data){
			var auth=window.parent.getAuth();
			$.ajax({
				type:"post",
				data:{caseWordid:casewordid,authenticityToken:auth},
				url:$Path+'/admin/caseWord/deleteCaseWordById',
				success:function(data){
					if(data.code==200){
						refreshWord();
					}
					else{
						parent.$.messager.alert('删除失败',data.msg,'error');
					}
				},
				error:function(data){
					parent.$.messager.alert('删除失败',"网络错误",'error');
				}
			})
		}
	})
}

function changeContent(context,id){
	ue.execCommand('inserthtml',context);
}

function printCourt(){
	ue.execCommand("print");
}

function exportCourt(){
	var content = ue.getAllHtml();
	$("#exportHtml").val(content);
	$("#authenticityToken").val(window.parent.getAuth());
	$("#exportCourt").submit();
}

function saveCourt(){
	var content = ue.getContent();
	var caseid = $("#caseid").val();
	var auth=window.parent.getAuth();
	$.ajax({
		type:"post",
		data:{"drCaseContent.caseid":caseid,"drCaseContent.content":content,authenticityToken:auth},
		url:$Path+'/admin/saveCaseContent',
		success:function(data){
			if(data.code!=200){
				parent.$.messager.alert('保存庭审笔录失败',data.msg,'error');
			}
		},
		error:function(data){
			parent.$.messager.alert('保存失败',"网络错误",'error');
		}
	})
}
/**
 * 开庭
 */
var lastTime='';
var isfind=true;
var timeFax;
function startCourt(){
	if(statTime){
		var date=new Date();
		if((date.getTime()-statTime.getTime())<60000){
			 $.messager.alert('警告','暂停时间小于一分钟，请稍作等待','warning');
			 return;
		}
	}
	var courtid=$("#courtid").val();
	var caseid=$("#caseid").val();
	var auth=window.parent.getAuth();
	window.parent.showloading();
	//向后台发送请求，开启转换线程。
	$.ajax({
		type:'POST',
		url:$Path+'/admin/startLive',
		data:{'courtid':courtid,'caseid':caseid,authenticityToken:auth},
		success:function(data){
			window.parent.hideloading();
			if(data.code==200){
				colseStartButton();
				openPaurseButton();
				openStopButton();
				statTime=new Date();
				//调取计时
				var timelength=data.results;
				TimeFunc(timelength);
				//长轮询
				isfind=true;
				findnew();
			}
			else{
				
				 parent.$.messager.alert('失败',data.msg,'error');
			}
		},
		error:function(){
			 window.parent.hideloading();
			 parent.$.messager.alert('失败','服务器开小差了~','error');
		}
	})
}
/**
 * 计算时间
 * @param leng
 */
function TimeFunc(leng){
	if(leng==''||leng==undefined){
		leng=0;
	}
	var intDiff=leng;
	timeFax=setInterval(function(){
		setTime(intDiff);
		intDiff++;
	},1000);
}
/**
 * 计算时间
 * @param data
 */
function setTime(intDiff){
	var hour=0,
	minute=0,
	second=0;
	hour=Math.floor(intDiff/(60*60));
	minute=Math.floor(intDiff/60)-(hour*60);
	second=Math.floor(intDiff)-(hour*60*60)-(minute*60);
	if(hour<=9){
		hour="0"+hour;
	}
	if(minute<=9){
		minute="0"+minute;
	}
	if(second<=9){
		second='0'+second;
	}
	$("#hourtxt").text(hour);
	$("#minutetxt").text(minute);
	$("#secondtxt").text(second);
}
/**
 * 轮询最新数据
 */
var rolename="";
function findnew(){
	var caseid=$("#caseid").val();
	try{
		//查找最后节点
		var body=ue.body;
		var lastNode=body.lastChild;
		//查找最后一个节点,以最后一个节点的最后一个<span>节点作为最后一次查询的时间
		if(lastNode.lastChild!=undefined){
			if(lastNode.lastChild.attributes!=undefined&&
				lastNode.lastChild.attributes.datastr!=undefined){
				lastTime=lastNode.lastChild.attributes.datastr.nodeValue;
			}
		}
		var firstNode=body.firstChild;
		//如果当前节点的时间戳为空，向前查找最后一个时间戳，直到时间戳不为空或者最开始的一个节点
		var preNode;
		while(lastTime==''){
			preNode=lastNode.previousSibling;
			if(preNode==null){
				break;
			}
			if(preNode!=null&&preNode.innerText==firstNode.innerText){
				break;
			}
			if(preNode.lastChild!=undefined){
				if(preNode.lastChild.attributes!=undefined&&
						preNode.lastChild.attributes.datastr!=undefined){
						lastTime=preNode.lastChild.attributes.datastr.nodeValue;
				}
			}
			lastNode=preNode
		}
		//延迟100ms
		setTimeout(function(){
		},200)
		
		$.ajax({
			type:'get',
			url:$Path+'/admin/getNewLine',
			data:{lastTime:lastTime,caseid:caseid},
			success:function(data){
				if(data.code==200){
					var results=data.results;
					if(results==null||results==''||results==undefined){
						if(isfind){
							findnew();
						}
						return false;
					}
					var body=ue.body;
					if(results.length>0){
						for(var i=0;i<results.length;i++){
							var body=ue.body;
							if(results[i].text==''||results[i].text==undefined){
								continue;
							}
							//如果最后一个节点的时间和当前时间相等，替换掉最后一个节点
							//没有换角色继续向后追加
							if(results[i].rolename==rolename){
								var newNode=document.createElement('span');
								newNode.setAttribute('datastr',results[i].beginTime);
								newNode.innerText=results[i].text;
	//							var childLast=lastNode.lastChild;
								if(results[i].beginTime==lastTime){
									if(lastNode.firstChild==undefined
											||lastNode.firstChild.attributes==undefined
											||lastNode.firstChild.attributes.datastr==undefined){
										rolename="";
										if(isfind){
											findnew();
										}
										return;
									}
									if(lastNode.firstChild.attributes.datastr.nodeValue==results[i].beginTime){
										newNode.innerText=results[i].rolename+':'+results[i].text;
										lastNode.replaceChild(newNode,lastNode.lastChild);
									}
									else{
										lastNode.replaceChild(newNode,lastNode.lastChild);
									}
								}
								else{
									lastNode.appendChild(newNode);
	//								lastNode=newNode;
								}
							}
							//如果换角色新加一行
							else{
								var parentNode=document.createElement('p');
								parentNode.setAttribute('datastr',results[i].beginTime);
								results[i].text==undefined?'':results[i].value;
								results[i].rolename==undefined?'':results[i].rolename;
								results[i].beginTime==undefined?'':results[i].beginTime
								parentNode.style.marginLeft='20px';
								body.appendChild(parentNode);
								var newNode=document.createElement('span');
								newNode.setAttribute('datastr',results[i].beginTime);
								newNode.innerText=results[i].rolename+':'+results[i].text;
								var ttnode=body.lastChild;
								ttnode.appendChild(newNode);
								lastNode=body.lastChild;
							}
							rolename=results[i].rolename;
							if(!$("#isScroll").is(':checked')){
								$(ue.window).scrollTop(ue.body.scrollHeight);
							}
						}
					}
					//没有点击闭庭或者休庭，继续轮询,延迟2秒
					if(isfind){
	//					setTimeout(function(){
							findnew();
	//					},2000);
						
					}
				}
				else{
					 isfind=false;
					 parent.$.messager.alert('失败',data.msg,'error');
				}
			},
//			error:function(data){
//				 isfind=false;
//				 parent.$.messager.alert('失败',"服务器开小差了~",'error');
//			}
		})
	}catch(e){
		findnew();
	}
}


/**
 * 闭庭
 */
var isCompel=false;
function stopcourt(){
	colseStopButton();
	//闭庭后关闭轮询任务，关闭读写线程,将内容保存
	var courtid=$("#courtid").val();
	var caseid=$("#caseid").val();
	var content=ue.getContent();
	var auth=window.parent.getAuth();
	window.parent.showloading();
	$.ajax({
		type:'POST',
		url:$Path+'/admin/stopLive',
		data:{'courtid':courtid,'caseid':caseid,authenticityToken:auth,content:content,isCompel:isCompel},
		success:function(data){
			window.parent.hideloading();
			if(data.code==200){
				colseStartButton();
				colsePaurseButton();
				colseStopButton();
				isfind=false;
				window.clearInterval(timeFax);
			}
			else if(data.code==905){
				parent.$.messager.confirm('失败','转换MP3格式失败，是否继续提交',function(data){
					if(data){
						isCompel=true;
						stopcourt();
					}
					else{
						colseStartButton();
						openPaurseButton();
						openStopButton();
					}
				});
			}
			else{
				openStopButton();
				parent.$.messager.alert('失败',data.msg,'error');
			}
		},
		error:function(){
			window.parent.hideloading();
			openStopButton();
			parent.$.messager.alert('失败','服务器开小差了~','error');
		}
	})
}
/**
 * 休庭
 */
function paursecourt(){
	if(statTime){
		var date=new Date();
		if((date.getTime()-statTime.getTime())<60000){
			 $.messager.alert('警告','启动时间小于一分钟，请稍作等待','warning');
			 return;
		}
	}
	var courtid=$("#courtid").val();
	var caseid=$("#caseid").val();
	var auth=window.parent.getAuth();
	isfind=false;
	window.clearInterval(timeFax);
	window.parent.showloading();
	$.ajax({
		type:'POST',
		url:$Path+'/admin/pauseLive',
		data:{'courtid':courtid,'caseid':caseid,authenticityToken:auth},
		success:function(data){
			window.parent.hideloading();
			if(data.code==200){
				statTime=new Date();
				openStartButton();
				colsePaurseButton();
				openStopButton();
				isfind=false;
				window.clearInterval(timeFax);
			}
			else{
				parent.$.messager.alert('失败',data.msg,'error');
			}
		},
		error:function(){
			window.parent.hideloading();
			parent.$.messager.alert('失败','服务器开小差了~','error');
		}
	})
}


function openStartButton(){
	$("#startCourt").attr("src",$Path+"/public/images/button_start_normal.png");
	$("#startCourt").removeClass("colseMouseClass");
	$("#startCourt").addClass("openMouseClass");
	$("#startCourt").removeAttr("disabled");
}

function colseStartButton(){
	$("#startCourt").attr("src",$Path+"/public/images/start_pressed.png");
	$("#startCourt").removeClass("openMouseClass");
	$("#startCourt").addClass("colseMouseClass");
	$("#startCourt").attr("disabled","disabled");
}

function openPaurseButton(){
	$("#paursecourt").attr("src",$Path+"/public/images/button_paurse_normal.png");
	$("#paursecourt").removeClass("colseMouseClass");
	$("#paursecourt").addClass("openMouseClass");
	$("#paursecourt").removeAttr("disabled");
}

function colsePaurseButton(){
	$("#paursecourt").attr("src",$Path+"/public/images/pause_pressed.png");
	$("#paursecourt").removeClass("openMouseClass");
	$("#paursecourt").addClass("colseMouseClass");
	$("#paursecourt").attr("disabled","disabled");
}

function openStopButton(){
	$("#stopcourt").attr("src",$Path+"/public/images/button_stop_normal.png");
	$("#stopcourt").removeClass("colseMouseClass");
	$("#stopcourt").addClass("openMouseClass");
	$("#stopcourt").removeAttr("disabled");
}

function colseStopButton(){
	$("#stopcourt").attr("src",$Path+"/public/images/stop_pressed.png");
	$("#stopcourt").removeClass("openMouseClass");
	$("#stopcourt").addClass("colseMouseClass");
	$("#stopcourt").attr("disabled","disabled");
}